package com.chr.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.chr.entity.Address;
import com.chr.service.AddressService;

import java.util.List;

/**
 * Created by tian on 2016/12/1.
 */

@Controller
public class IndexController {

	@Autowired
	AddressService addressService;

	@RequestMapping({ "/", "/index" })
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/address", method = RequestMethod.GET)
	@ResponseBody
	public List<Address> getAllAddress() {

		List<Address> allAddress = addressService.findAll();
		if (allAddress.isEmpty()) {
			for (int i = 0; i < 10; i++) {
				Address address = new Address("city" + i, "province" + i);
				allAddress.add(addressService.saveAndFlush(address));
			}
			//model.addAttribute("data", allAddress);
		}
		return allAddress;
	}
	
/*	@RequestMapping(value = "/address", method = RequestMethod.GET)
	//@ResponseBody
	public String getAllAddress(Model model) {

		List<Address> allAddress = addressService.findAll();
		if (allAddress.isEmpty()) {
			for (int i = 0; i < 10; i++) {
				Address address = new Address("city" + i, "province" + i);
				allAddress.add(addressService.saveAndFlush(address));
			}
			model.addAttribute("allAddress", allAddress);
		}
		return "/index";
	}*/
	
	

	@RequestMapping(value = "/address", method = RequestMethod.POST)
	@ResponseBody
	public Address saveAddress(@RequestBody JSONObject object) {
		Address address = new Address(object.get("city").toString(), object.get("province").toString());
		addressService.saveAndFlush(address);
		return address;
	}

	@RequestMapping(value = "/address/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public Address updateAddress(@RequestBody JSONObject object) {
		Address address = new Address(Long.valueOf(object.get("id").toString()), object.get("city").toString(),
				object.get("province").toString());
		addressService.updateAddress(address);
		return address;
	}

	@RequestMapping(value = "/address/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public void deleteAddress(@PathVariable("id") Long id) {
		/*Long id=Long.valueOf(object.get("id").toString());*/
		
		addressService.dateleAddress(id);
	}

}
